<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\Child;
use App\Models\CurrentChild;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class CurrentChildController extends BaseController
{
    public function index(Request $request)
    {

        $this->validate($request, [
            'child_id' => 'required|integer|exists:children,id',
            'device_code' => 'required|string|exists:devices,code',
        ], [], []);

        $data = $request->only(['child_id', 'device_code']);
        $child = Child::find($data['child_id']);

        $user = $this->getUser();
        if (!$user->can('allow', $child)){
              return $this->json([], config("apicode.noAuth.msg"), config("apicode.noAuth.code"));
        }

        if (CurrentChild::updateOrCreate(['device_code'=>$data['device_code'], 'user_id'=>$user->id],['child_id'=> $data['child_id']] )){
            $user->children()->where('current', 1)->update(['current'=> 0]);
            $child->update(['current'=>1]);

            return $this->json([]);
        }
        return $this->json([], config("apicode.serverError.msg"), config("apicode.serverError.code"));

    }

}
